package com.shiwaixiangcun.authz.web.controller;

import com.shiwaixiangcun.authz.oauth.OAuthTokenxRequest;
import com.shiwaixiangcun.authz.oauth.token.OAuthTokenHandleDispatcher;
import com.shiwaixiangcun.core.web.response.MonkeyResponseDto;
import com.shiwaixiangcun.core.web.response.ResponseCode;
import com.shiwaixiangcun.utils.WebUtils;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 2015/7/3
 * <p>
 * URL: oauth2/token
 *
 * @author SilentWu
 */
@Controller
@RequestMapping("oauth2/")
public class OauthTokenController {


    /**
     * Handle grant_types as follows:
     * <p>
     * grant_type=authorization_code
     * grant_type=password
     * grant_type=refresh_token
     * grant_type=client_credentials
     *
     * @param request  HttpServletRequest
     * @param response HttpServletResponse
     * @throws Exception
     */
    @RequestMapping(value = "token", method = RequestMethod.POST)
    public void authorize(HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
            OAuthTokenxRequest tokenRequest = new OAuthTokenxRequest(request);

            OAuthTokenHandleDispatcher tokenHandleDispatcher = new OAuthTokenHandleDispatcher(tokenRequest, response);
            tokenHandleDispatcher.dispatch();
        } catch (OAuthProblemException e) {
            e.printStackTrace();
            //exception
            MonkeyResponseDto responseDto = new MonkeyResponseDto();
            responseDto.fail(ResponseCode.OAUTH2_GRANT_TYPE_ERROR, e.getMessage());
            WebUtils.writeJSON(response, responseDto);
        }
    }



}
